package com.atldy.cloudgrains.advice;

import com.atldy.cloudgrains.exception.BusinessException;
import com.atldy.common.vo.ResultResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import static com.atldy.common.enums.StatusCodeEnum.SYSTEM_ERROR;
import static com.atldy.common.enums.StatusCodeEnum.VALID_ERROR;

/**
 * @version 1.0
 * @Author: li-dong-yang
 * @CreateTime: 2021-09-15 17:07
 * @Description： 全局异常处理
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionAdvice {


    /**
     * 处理服务异常
     *
     * @param e 异常
     * @return 接口异常信息
     */
    @ExceptionHandler(value = BusinessException.class)
    public ResultResponse<?> errorHandler(BusinessException e) {
        return new ResultResponse(e.getCode(), e.getMessage());
    }

    /**
     * 处理参数校验异常
     *
     * @param e 异常
     * @return 接口异常信息
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultResponse<?> errorHandler(MethodArgumentNotValidException e) {
        ResultResponse<String> response = new ResultResponse<>(VALID_ERROR.getCode(), VALID_ERROR.getDesc());
        response.setData(e.getMessage());
        log.error("param check has error: [{}] [{}]", e.getMessage(), e);
        return response;
    }

    /**
     * 处理系统异常
     *
     * @param e 异常
     * @return 接口异常信息
     */
    @ExceptionHandler(value = Exception.class)
    public ResultResponse<?> errorHandler(Exception e) {
        e.printStackTrace();
        return new ResultResponse(SYSTEM_ERROR.getCode(), SYSTEM_ERROR.getDesc());
    }


}